<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item>-->
      <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
      <!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
      <!--      </el-form-item>-->
      <el-header class="chat-header">
        <div class="header-actions">
          <el-button type="text" icon="el-icon-back" @click="goback()">返回首页</el-button>
          <!--            <el-button type="text" icon="el-icon-share"></el-button>-->
        </div>
        <h2>{{ topTitle }}</h2>
        <!--          <h2>{{ 内容由烟叶知识库AI 生成，请仔细甄别 }}</h2>-->

      </el-header>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:model:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:model:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:model:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:model:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="id"/>
      <el-table-column label="模型名称" align="center" prop="remark"/>
      <el-table-column label="模型路径" align="center" prop="updateBy" width="180">
        <!-- 自定义单元格模板：通过 slot-scope="scope" 获取当前行数据 -->
        <template slot-scope="scope">
          <!-- 1. 绑定路径：scope.row.模型路径字段名（此处用 modelPath 示例） -->
          <!-- 2. 处理空值：如果路径为空，显示“无”而非空链接 -->
          <a
            :href="scope.row.updateBy"
            target="_blank"
            v-if="scope.row.updateBy"
            style="color: #409EFF; text-decoration: underline;"
          >
            下载模型
          </a>
          <span v-else>无</span> <!-- 路径为空时显示的内容 -->
        </template>
      </el-table-column>
      <el-table-column label="提取码" align="center" prop="status"/>
      <el-table-column label="试验田位置信息" align="center" prop="testFieldSpatialInfo"/>
      <el-table-column label="土壤营养数据" align="center" prop="soilNutrientData"/>
      <el-table-column label="图像数据" align="center" prop="tobaccoLeafImageData" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.tobaccoLeafImageData" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="图像特征" align="center" prop="tobaccoLeafFeature"/>
      <el-table-column label="特征融合数据" align="center" prop="fusedMultimodalFeature"/>
      <el-table-column label="品质评估结果" align="center" prop="tobaccoQualityEvaluation"/>
      <el-table-column label="关系分析结果" align="center">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.correlationAnalysisResult" placement="top">
            <span>{{
                scope.row.correlationAnalysisResult.slice(0, 15)
              }}{{ scope.row.correlationAnalysisResult.length > 15 ? '...' : '' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-arrow-right"
            @click="handelRunModel(scope.row)"

            v-hasPermi="['system:model:edit']"
          >运行模型
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['system:model:remove']"-->
          <!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="showModelLossDialog"
      :title="modelTitle"
      width="50%"
      :close-on-click-modal="false"
      @open="startProgress"
    >
      <!-- 图片依然显示 -->
<!--      <img :src="imageLossUrl" alt="展示图片" style="width: 100%;">-->

      <!-- 进度条区域 -->
      <div v-if="!progressComplete" style="margin-top: 20px;">
        <el-progress
          :percentage="progressPercent"
          stroke-width="6"
          style="margin-bottom: 10px;"
        ></el-progress>
<!--        <p style="text-align: center; color: #666;">-->
<!--          正在准备分析数据，请等待 {{ Math.ceil((10 - progressPercent / 10) * 10) / 10 }} 秒-->
<!--        </p>-->
      </div>
      <!-- 自定义底部按钮，进度完成后才显示 -->
      <span slot="footer" class="dialog-footer" v-if="progressComplete">
    <el-button type="primary" @click="gotoAi()">开始分析土壤养分和烟叶品质关联关系</el-button>
    <el-button @click="showModelLossDialog = false">关闭</el-button>
  </span>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模型管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模型名称" prop="testFieldSpatialInfo">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="采集时间" prop="dataCollectionTime">
          <el-date-picker clearable
                          v-model="form.dataCollectionTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择采集时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="试验田位置信息" prop="testFieldSpatialInfo">
          <el-input v-model="form.testFieldSpatialInfo" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="土壤营养数据" prop="soilNutrientData">
          <el-input v-model="form.soilNutrientData" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="图像数据" prop="tobaccoLeafImageData">
          <image-upload v-model="form.tobaccoLeafImageData"/>
        </el-form-item>
        <el-form-item label="图像特征" prop="tobaccoLeafFeature">
          <el-input v-model="form.tobaccoLeafFeature" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="特征融合数据" prop="fusedMultimodalFeature">
          <el-input v-model="form.fusedMultimodalFeature" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listModel, getModel, delModel, addModel, updateModel} from "@/api/system/model";

export default {
  name: "Model",
  data() {
    return {

      //所选择的模型
      modelName: '',
      //损失图片
      imageLossUrl: '/loss/train_loss.png',
      progressPercent: 0,  // 进度百分比
      progressComplete: false,  // 进度是否完成
      progressTimer: null,  // 定时器
      modelTitle:'正在加载模型，请稍等...',
      //是否打开运行模型的图
      showModelLossDialog: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模型管理表格数据
      modelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        soilNutrientData: null,
        tobaccoQualityEvaluation: null,
        correlationAnalysisResult: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {

    const method = this.$route.query.method;
    console.log("method: ", method)
    // if(method=="hidden"){
    //   this.$store.dispatch('app/toggleSideBarHide', true);
    //   document.querySelector('.navbar').style.display = "none";
    //   document.querySelector('.tags-view-container').style.display = "none"
    // }
//     else{
//       // 打开左侧导航栏（通过 Vuex 状态）
//       this.$store.dispatch('app/toggleSideBarHide', false); // 与关闭时的参数相反
// // 显示顶部导航栏
//       document.querySelector('.navbar').style.display = "block"; // 还原为默认显示状态
// // 显示标签栏
//       document.querySelector('.tags-view-container').style.display = "block"; // 还原为默认显示状态
//     }
    this.getList();

    // document.title = "知识库";

  },
  methods: {
    /** 查询模型管理列表 */
    getList() {
      this.loading = true;
      listModel(this.queryParams).then(response => {
        this.modelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dataCollectionTime: null,
        testFieldSpatialInfo: null,
        soilNutrientData: null,
        tobaccoLeafImageData: null,
        tobaccoLeafFeature: null,
        fusedMultimodalFeature: null,
        tobaccoQualityEvaluation: null,
        correlationAnalysisResult: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模型管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getModel(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模型管理";
      });
    },

    /** 运行模型操作 */
    handelRunModel(row) {

      this.modelName = row.remark
      this.showModelLossDialog = true;
      // this.openLoading(row.remark);

      // 使用 setTimeout 延迟 5 秒（5000 毫秒）执行回调函数
      // setTimeout(() => {
      //
      //   this.showModelLossDialog = true;
      //   this.$modal.closeLoading();
      // }, 5000);

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateModel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addModel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除模型管理编号为"' + ids + '"的数据项？').then(function () {
        return delModel(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/model/export', {
        ...this.queryParams
      }, `model_${new Date().getTime()}.xlsx`)
    },
    openLoading(model) {
      this.$modal.loading(model + "模型正在训练已有数据，请稍候！");
    },
    startProgress() {
      // 重置进度状态
      this.progressPercent = 0;
      this.progressComplete = false;

// 清除旧定时器
      if (this.progressTimer) clearInterval(this.progressTimer);

      /* ===== 随机 10–15 秒 ===== */
      const totalSec = Math.floor(Math.random() * 6) + 10;   // 10~15 秒
      const stepInterval = 100;                              // 每 100 ms 更新一次
      const totalSteps = (totalSec * 1000) / stepInterval;   // 需要更新的总次数
      const stepSize = 100 / totalSteps;                     // 每次增加的百分比

      this.progressTimer = setInterval(() => {
        this.progressPercent += stepSize;

        // 保留2位小数
        this.progressPercent = Math.min(100, Number(this.progressPercent.toFixed(2)));

        if (this.progressPercent >= 100) {
          clearInterval(this.progressTimer);
          this.progressComplete = true;
          this.progressTimer = null;
          this.progressPercent = 100; // 确保最终显示100.00%
          this.modelTitle = '模型加载完成，点击右下角开始分析';
        }
      }, stepInterval);
    },
    // 组件销毁时清除定时器，防止内存泄漏
    beforeDestroy() {
      if (this.progressTimer) {
        clearInterval(this.progressTimer);
      }
    },
    gotoAi() {

      this.$router.push({
        path: "/ai",
        query: {
          name: this.modelName // 传递参数name
        }
      }).catch(() => {
      });
    },
    goback() {
// 返回上一页
      this.$router.push({
        path: "/index",
        query: {
          name: this.modelName // 传递参数name
        }
      }).catch(() => {
      });
    }

  }
};
</script>
